package cn.stylefeng.guns.modular.tool.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.core.util.DateUtil;
import cn.stylefeng.guns.core.util.justApi;
import cn.stylefeng.guns.modular.basic.entity.BasicCustomer;
import cn.stylefeng.guns.modular.basic.service.BasicCustomerService;
import cn.stylefeng.guns.modular.tool.entity.ToolExpress;
import cn.stylefeng.guns.modular.tool.entity.ToolExpressSum;
import cn.stylefeng.guns.modular.tool.entity.ToolWave;
import cn.stylefeng.guns.modular.tool.model.params.ToolExpressExcelParam;
import cn.stylefeng.guns.modular.tool.model.params.ToolExpressParam;
import cn.stylefeng.guns.modular.tool.model.params.ToolExpressScanParam;
import cn.stylefeng.guns.modular.tool.model.params.ToolExpressSumParam;
import cn.stylefeng.guns.modular.tool.model.params.ToolGoodsInstallParam;
import cn.stylefeng.guns.modular.tool.model.params.ToolWaveParam;
import cn.stylefeng.guns.modular.tool.model.result.ToolExpressExcelResult;
import cn.stylefeng.guns.modular.tool.model.result.ToolExpressResult;
import cn.stylefeng.guns.modular.tool.model.result.ToolGoodsInstallResult;
import cn.stylefeng.guns.modular.tool.model.result.ToolWaveResult;
import cn.stylefeng.guns.modular.tool.service.ToolExpressExcelService;
import cn.stylefeng.guns.modular.tool.service.ToolExpressScanService;
import cn.stylefeng.guns.modular.tool.service.ToolExpressService;
import cn.stylefeng.guns.modular.tool.service.ToolExpressSumService;
import cn.stylefeng.guns.modular.tool.service.ToolGoodsInstallService;
import cn.stylefeng.guns.modular.tool.service.ToolTaskArrangeService;
import cn.stylefeng.guns.modular.tool.service.ToolWaveService;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;

/**
 * 快递统计管理控制器
 */
@Controller
@RequestMapping("/toolExpress")
public class ToolExpressController extends BaseController {

    private String PREFIX = "/tool/toolExpress";

    @Autowired
    private ToolExpressService toolExpressService;

    @Autowired
    private BasicCustomerService basicCustomerService;
    
    @Autowired
    private UserService userService;
    
    private Lock lock = new ReentrantLock();
    
    /**
     * 跳转到主页面
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "/toolExpress.html";
    }
    
    /**
     * 跳转到导入	快递明细	页面
     */
    @RequestMapping("toimportExcel")
    public String toimportExcel(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/import.html";
    }
    
    /**
     * 跳转到导入	已分配	页面
     */
    @RequestMapping("toimportExcel3")
    public String toimportExcel3() {
        return PREFIX + "/import3.html";
    }
    
    /**
     * 跳转到导入	作业量	页面
     */
    @RequestMapping("toimportExcel4")
    public String toimportExcel4(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/import4.html";
    }
    
    /**
     * 跳转到导入	工作安排	页面
     */
    @RequestMapping("toimportExcel8")
    public String toimportExcel8() {
        return PREFIX + "/import8.html";
    }

    @Autowired
    private ToolExpressSumService toolExpressSumService;

    /**
     * 快递明细
     * 上传excel   
     */
	@RequestMapping(value = "/importExceNewmethodl" , method = {RequestMethod.POST} )
    @ResponseBody
    public ResponseData importExceNewmethodl(@RequestPart("file") MultipartFile file,Long waveId,Long customerId)  {
		ResponseData data = new ResponseData();
		lock.lock();//获取锁
		try {
			data = toolExpressService.getExceldata(file,waveId,customerId,data);//处理导入数据
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();//释放锁
		}
        return data;
    }
	
    /**
     * 工作安排
     * 上传excel   
     */
	@RequestMapping(value = "/importExceNewmethodl8" , method = {RequestMethod.POST} )
    @ResponseBody
    public ResponseData importExceNewmethodl8(@RequestPart("file") MultipartFile file,Long waveId)  {
		ResponseData data = new ResponseData();
		lock.lock();//获取锁
		try {
			data = toolTaskArrangeService.getExceldata8(file,waveId,data);//处理导入数据
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();//释放锁
		}
        return data;
    }

    @Autowired
    private ToolExpressExcelService toolExpressExcelService;
	
    /**
     * 已分配
     * 上传excel   
     */
	@RequestMapping(value = "/importExceNewmethodl3" , method = {RequestMethod.POST} )
    @ResponseBody
    public ResponseData importExceNewmethodl3(@RequestPart("file") MultipartFile file,Long waveId)  {
		ResponseData data = new ResponseData();
		lock.lock();//获取锁
		try {
			data = toolExpressService.getExceldata3(file,waveId,data);//处理导入数据
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();//释放锁
		}
        return data;
    }
	
    /**
     * 作业量
     * 上传excel   
     */
	@RequestMapping(value = "/importExceNewmethodl4" , method = {RequestMethod.POST} )
    @ResponseBody
    public ResponseData importExceNewmethodl4(@RequestPart("file") MultipartFile file,Long waveId,Long customerId)  {
		ResponseData data = new ResponseData();
		lock.lock();//获取锁
		try {
			data = toolExpressService.getExceldata4(file,waveId,customerId,data);//处理导入数据
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();//释放锁
		}
        return data;
    }

    @Autowired
    private ToolTaskArrangeService toolTaskArrangeService;
    
    /**
     * 下载订单模板
     * @throws ServletException , IOException
     */
    @RequestMapping("downloadExcelTemplate")
    public void downloadExcelTemplate(HttpServletRequest request,HttpServletResponse response) throws ServletException ,IOException {
        String path = "assets/excel/toolExpress.xlsx";
        try {
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);
            OutputStream  outputStream = response.getOutputStream();
            //设置下载的文件类型
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //设置下载文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("快递明细模板" + ".xlsx").getBytes(), "iso-8859-1"));
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 下载订单模板
     * @throws ServletException , IOException
     */
    @RequestMapping("downloadExcelTemplate8")
    public void downloadExcelTemplate8(HttpServletRequest request,HttpServletResponse response) throws ServletException ,IOException {
        String path = "assets/excel/toolTaskArrange.xlsx";
        try {
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);
            OutputStream  outputStream = response.getOutputStream();
            //设置下载的文件类型
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //设置下载文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("工作安排导入模板" + ".xlsx").getBytes(), "iso-8859-1"));
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 下载订单模板
     * @throws ServletException , IOException
     */
    @RequestMapping("downloadExcelTemplateF")
    public void downloadExcelTemplateF(HttpServletRequest request,HttpServletResponse response) throws ServletException ,IOException {
        String path = "assets/excel/toolExpressFp.xlsx";
        try {
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);
            OutputStream  outputStream = response.getOutputStream();
            //设置下载的文件类型
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //设置下载文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("作业分配模板" + ".xlsx").getBytes(), "iso-8859-1"));
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 下载订单模板
     * @throws ServletException , IOException
     */
    @RequestMapping("downloadExcelTemplate4")
    public void downloadExcelTemplate4(HttpServletRequest request,HttpServletResponse response) throws ServletException ,IOException {
        String path = "assets/excel/toolExpressZy.xlsx";
        try {
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);
            OutputStream  outputStream = response.getOutputStream();
            //设置下载的文件类型
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //设置下载文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("预包、退货整理作业量模板" + ".xlsx").getBytes(), "iso-8859-1"));
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 新增页面
     */
    @RequestMapping("/add")
    public String add() {
        return PREFIX + "/toolExpress_add.html";
    }

    /**
     * 编辑页面
     */
    @RequestMapping("/edit")
    public String edit() {
        return PREFIX + "/toolExpress_edit.html";
    }

    /**
     * 新增接口
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(ToolExpressParam toolExpressParam) {
    	User user = userService.getcurrentUser();
    	toolExpressParam.setDeptId(user.getDeptId());
    	toolExpressParam.setCreateUserName(user.getName());
        this.toolExpressService.add(toolExpressParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(ToolExpressParam toolExpressParam) {
        this.toolExpressService.update(toolExpressParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(ToolExpressParam toolExpressParam) {
        this.toolExpressService.delete(toolExpressParam);
        return ResponseData.success();
    }

    /**
     * 批量删除接口
     */
    @RequestMapping("/btnRevoke")
    @ResponseBody
    public ResponseData btnRevoke(Integer[] ids) {
    	for (Integer id : ids) {
            ToolExpressParam toolExpressParam = new ToolExpressParam();
            toolExpressParam.setId(id);
			this.toolExpressService.delete(toolExpressParam );
		}
        return ResponseData.success();
    }
    
    /**
     * 清空接口
     */
    @RequestMapping("/btnRevoke2")
    @ResponseBody
    public ResponseData btnRevoke2(ToolExpressParam expressParam) {
        toolExpressService.deleteBySpec(expressParam);
        
        ToolExpressExcelParam toolExpressExcelParam = new ToolExpressExcelParam();
        toolExpressExcelParam.setWaveId(expressParam.getWaveId());
        toolExpressExcelService.deleteBySpec(toolExpressExcelParam);
        
        ToolExpressSumParam expressSumParam = new ToolExpressSumParam();
        expressSumParam.setWaveId(expressParam.getWaveId());
        toolExpressSumService.deleteBySpec(expressSumParam);
        return ResponseData.success();
    }

    @Autowired
    private ToolWaveService toolWaveService;

    /**
     * 批量转入下一日接口
     */
    @RequestMapping("/btnday")
    @ResponseBody
    public ResponseData btnday(Integer[] ids,Long waveId) {
		lock.lock();//获取锁
		try {
	    	ToolWave toolWave = toolWaveService.getById(waveId);
	    	User user = userService.getcurrentUser();
	    	ToolWaveParam toolWaveParam = new ToolWaveParam();
	    	toolWaveParam.setDeptId(user.getDeptId());
	    	toolWaveParam.setWaveName(DateUtil.getXdat(toolWave.getWaveName()));
	    	ToolWaveResult r = toolWaveService.findBySpec(toolWaveParam,user.getOperateId());
	    	if(r == null) {
	    		toolWaveParam.setCreateUserName(user.getName());
	    		toolWaveService.add(toolWaveParam);
	    		r = toolWaveService.findBySpec(toolWaveParam,user.getOperateId());
	    	}
	    	List<ToolExpressParam> savelist = new ArrayList<ToolExpressParam>();
	    	for (Integer id : ids) {
	    		ToolExpress toolExpress = toolExpressService.getById(id);
	    		toolExpress.setWaveId(Long.parseLong(r.getId().toString()) );
	    		toolExpress.setId(null);
	    		ToolExpressParam toolExpressParam = new ToolExpressParam();
	    		ToolUtil.copyProperties(toolExpress, toolExpressParam);
	    		toolExpressParam.setLastDay("1");
	    		savelist.add(toolExpressParam);
	            ToolExpressParam toolExpressParam2 = new ToolExpressParam();
	            toolExpressParam2.setId(id);
				this.toolExpressService.delete(toolExpressParam2 );
				
				ToolExpressExcelParam excelParam = new ToolExpressExcelParam();
				excelParam.setLastDay("1");
				excelParam.setOutNumber(toolExpressParam.getV1());
				excelParam.setWaveId(Long.parseLong(r.getId().toString()));
				toolExpressExcelService.updateBySpec2(excelParam);
			}
	    	if(savelist.size()>0) {
	    		toolExpressService.saveBatchList(savelist);
				ToolExpressParam expressParam = new ToolExpressParam();
				expressParam.setWaveId(Long.parseLong(r.getId().toString()) );
				List<ToolExpressResult> list = toolExpressService.findListBySpecSum(expressParam);
				int z = 1;
				List<ToolExpressSumParam> listadd = new ArrayList<ToolExpressSumParam>();
				for (ToolExpressResult r2 : list) {
					ToolExpressSumParam sumParam = new ToolExpressSumParam();
					sumParam.setWaveId(Long.parseLong(r.getId().toString()));
					sumParam.setGoodsNumber(r2.getGoodsNumber());
					sumParam.setNum(r2.getNum()+"");
					sumParam.setOrderNum(r2.getV1());
					sumParam.setSumNum(r2.getV2());
					sumParam.setState("待配");
					sumParam.setV1(z+"");
					sumParam.setV2(r2.getV1());
					listadd.add(sumParam);
					z++;
				}
				if(listadd.size()>0) {
					ToolExpressSumParam ToolExpressSumParamdelete = new ToolExpressSumParam();
					ToolExpressSumParamdelete.setWaveId(Long.parseLong(r.getId().toString()));
					toolExpressSumService.deleteBySpec(ToolExpressSumParamdelete);
					toolExpressSumService.saveBatchList(listadd);
				}
	    	}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();//释放锁
		}
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(ToolExpressParam toolExpressParam) {
        ToolExpress detail = this.toolExpressService.getById(toolExpressParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(ToolExpressParam toolExpressParam,String condition,String startTime,String endTime ) {
    	if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
    		toolExpressParam.setV1("'"+startTime+"' and '"+endTime+"'");
		} 
        return this.toolExpressService.findPageBySpec(toolExpressParam,condition);
    }

    /**
     * 查询列表
     */
    @ResponseBody
    @RequestMapping("/findlist")
    public LayuiPageInfo findlist(ToolExpressParam toolExpressParam,String condition,String startTime,String endTime ) {
    	if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
    		toolExpressParam.setV3("'"+startTime+"' and '"+endTime+"'");
		} else if (startTime == null && endTime == null){
			startTime = DateUtil.getDate();
			endTime = DateUtil.getDate();
			toolExpressParam.setV3("'"+startTime+"' and '"+endTime+"'");
		}
    	if (toolExpressParam.getV4() == null) {
    		toolExpressParam.setV4("已配");
		}
        return this.toolExpressService.findPageBySpecFind(toolExpressParam,condition);
    }

    /**
     * 查询列表
     */
    @ResponseBody
    @RequestMapping("/list2")
    public LayuiPageInfo list2(ToolExpressParam toolExpressParam,String condition,String startTime,String endTime ) {
    	if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
    		toolExpressParam.setV1("'"+startTime+"' and '"+endTime+"'");
		} 
        return this.toolExpressService.findPageBySpec2(toolExpressParam,condition);
    }
    
    /**
     * 跳转
     * 波次单号列表页面
     */
    @RequestMapping("mingxi")
    public String mingxi() {
        return PREFIX + "/wellenList.html";
    }

    /**
     * 查询列表
     */
    @ResponseBody
    @RequestMapping("/wellenList")
    public LayuiPageInfo wellenList(ToolExpressParam toolExpressParam,String condition) {
        return this.toolExpressService.findwellenPageBySpec(toolExpressParam,condition);
    }

    /**
     * 批量删除接口
     */
    @RequestMapping("/wellenbtnDelete")
    @ResponseBody
    public ResponseData wellenbtnDelete(Integer[] ids) {
    	for (Integer id : ids) {
    		ToolExpress toolExpress = toolExpressService.getById(id);

            ToolExpressExcelParam toolExpressExcelParam = new ToolExpressExcelParam();
            toolExpressExcelParam.setWaveId(toolExpress.getWaveId());
            toolExpressExcelParam.setWellen(toolExpress.getWellen());
            toolExpressExcelParam.setOrderNumber(toolExpress.getOrderNumber());
            toolExpressExcelService.deleteBySpec(toolExpressExcelParam);
            
            ToolExpressScanParam toolExpressScanParam = new ToolExpressScanParam();
            toolExpressScanParam.setWaveId(toolExpress.getWaveId());
            toolExpressScanParam.setV1(toolExpress.getWellen());
            toolExpressScanParam.setOrderNumber(toolExpress.getOrderNumber());
            this.toolExpressScanService.deleteBySpec(toolExpressScanParam);
    		
            ToolExpressParam toolExpressParam = new ToolExpressParam();
            toolExpressParam.setId(id);
			this.toolExpressService.delete(toolExpressParam);

			ToolExpressParam expressParam2 = new ToolExpressParam();
			expressParam2.setWaveId(toolExpress.getWaveId());
			List<ToolExpressResult> list2 = toolExpressService.findListBySpecSum(expressParam2);
			int z = 1;
			List<ToolExpressSumParam> listadd2 = new ArrayList<ToolExpressSumParam>();
			for (ToolExpressResult r : list2) {
				ToolExpressSumParam sumParam = new ToolExpressSumParam();
				sumParam.setWaveId(toolExpress.getWaveId());
				sumParam.setCustomerId(r.getCustomerId());
				sumParam.setCustomerName(r.getCustomerName());
				sumParam.setGoodsNumber(r.getGoodsNumber());
				sumParam.setNum(r.getNum()+"");
				sumParam.setOrderNum(r.getV1());
				sumParam.setSumNum(r.getV2());
				sumParam.setState("待配");
				sumParam.setV1(z+"");
				sumParam.setV2(r.getV1());
				sumParam.setDeptId(r.getDeptId());
				listadd2.add(sumParam);
				z++;
			}
			if(listadd2.size()>0) {
				ToolExpressSumParam ToolExpressSumParamdelete = new ToolExpressSumParam();
				ToolExpressSumParamdelete.setWaveId(toolExpress.getWaveId());
				toolExpressSumService.deleteBySpec(ToolExpressSumParamdelete);
				toolExpressSumService.saveBatchList(listadd2);
			}
		}
        return ResponseData.success();
    }

    @Autowired
    private ToolExpressScanService toolExpressScanService;

}


